/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-09-05 08:22:44
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-09-05 08:55:18
 * @FilePath: /react18-vite-admin/src/service/useMessage.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { message } from 'antd';
import type { ArgsProps } from 'antd/es/message/interface';
import { ReplaySubject, type Subscription } from 'rxjs';
import { useEffect } from 'react';

export const messageSubject = new ReplaySubject<ArgsProps>(1);
const message$ = messageSubject.pipe();
let subcription: Subscription | undefined;

export const success = (opt: Omit<ArgsProps, 'type'>) => {
    messageSubject.next({
        ...opt,
        type: 'success'
    });
};

export const error = (opt: Omit<ArgsProps, 'type'>) => {
    messageSubject.next({
        ...opt,
        type: 'error'
    });
};

export const info = (opt: Omit<ArgsProps, 'type'>) => {
    messageSubject.next({
        ...opt,
        type: 'info'
    });
};

export const warning = (opt: Omit<ArgsProps, 'type'>) => {
    messageSubject.next({
        ...opt,
        type: 'warning'
    });
};

export const loading = (opt: Omit<ArgsProps, 'type'>) => {
    messageSubject.next({
        ...opt,
        type: 'loading'
    });
};

export const open = (opt: ArgsProps) => {
    messageSubject.next(opt);
};

export const useMessage = () => {
    const [messageApi, contextHolder] = message.useMessage();

    useEffect(() => {
        subcription?.unsubscribe();
        subcription = message$.subscribe((opt) => {
            messageApi.open(opt);
        });

        return () => {
            subcription?.unsubscribe();
        };
    }, [messageApi]);

    return {
        contextHolder
    };
};
